package vip.mtdp.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * @author wangguoqing
 * @Description 时间统计处理器
 * @date 2019/12/5 11:07
 */
@Slf4j
@Service("requestTimeFilter")
public class RequestTimeFilter implements GlobalFilter, Ordered {

    /**请求开始时间**/
    private static String REQUEST_BEGIN_TIME = "request_begin_time";

    /**
     * Process the Web request and (optionally) delegate to the next {@code WebFilter}
     * through the given {@link GatewayFilterChain}.
     *
     * @param exchange the current server exchange
     * @param chain    provides a way to delegate to the next filter
     * @return {@code Mono<Void>} to indicate when request processing is complete
     */
    @Override
    public Mono<Void> filter(final ServerWebExchange exchange, GatewayFilterChain chain) {

        Map<String,Object> map = exchange.getAttributes();
        map.put(REQUEST_BEGIN_TIME,System.currentTimeMillis());
        //pre,post;先执行pre,根据order 的排序执行,再执行post,post在then语句中执行
        return chain.filter(exchange).then(Mono.fromRunnable(()->{
            Long beginTime = exchange.getAttribute(REQUEST_BEGIN_TIME);
            if(beginTime != null){
                Long endTime = System.currentTimeMillis();
                Long diffValue = endTime - beginTime;
                StringBuffer sb = new StringBuffer();
                sb.append(exchange.getRequest().getURI().getRawPath())
                  .append(" ").append(diffValue).append(" ms");
                log.info("=====> {}",sb.toString());
            }
        }));
    }

    /**
     * Get the order value of this object.
     * <p>Higher values are interpreted as lower priority. As a consequence,
     * the object with the lowest value has the highest priority (somewhat
     * analogous to Servlet {@code load-on-startup} values).
     * <p>Same order values will result in arbitrary sort positions for the
     * affected objects.
     *
     * @return the order value
     * @see #HIGHEST_PRECEDENCE
     * @see #LOWEST_PRECEDENCE
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
